<template>
  <div v-if="isTrue">
    <el-form
      :model="form"
      ref="form"
      label-width="144px"
      class="ccui-form elInput"
      :rules="rules"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="填报单位：" prop="reportInOrgId">
            <el-select
              v-model="form.reportInOrgId"
              placeholder="请选择填报单位"
              @change="changeReportInOrgId"
            >
              <el-option
                v-for="item in reportOptions"
                :key="item.orgId"
                :label="item.name"
                :value="item.orgId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门：" prop="departName">
            <el-select
              ref="selectTree"
              v-model="form.departName"
              placeholder="请选择部门"
              popper-class="popperTreeSelect"
            >
              <el-option label="" value="">
                <el-tree
                  :data="departOptions"
                  :props="{ children: 'child', label: 'abbrName' }"
                  @node-click="handleNodeClick"
                >
                  <span
                    :class="{
                      'depart-tree-node': form.departName === node.data.abbrName
                    }"
                    slot-scope="{ node }"
                  >
                    {{ node.data.abbrName }}
                  </span>
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="盘点单编号：" prop="inventoryCode">
            <el-input v-model="form.inventoryCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点单名称：" prop="inventoryName">
            <el-input
              maxlength="300"
              v-model="form.inventoryName"
              placeholder="请输入盘点单名称"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="仓库：" prop="warehouseName">
            <el-input
              v-model="form.warehouseName"
              placeholder="请选择仓库"
              class="ccui-form-longInput"
              disabled
            ></el-input>
            <el-button
              plain
              type="single-number"
              style="margin-left: 10px"
              @click="handleWarehouse"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称：" prop="projectName">
            <el-input v-model="form.projectName" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="本位币币种：" prop="standardMoney">
            <el-input v-model="form.standardMoney" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计税方式：" prop="valoremMethod">
            <el-input v-model="form.valoremMethod" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="分类名称：" prop="categoryName">
            <el-input v-model="form.categoryName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件张数：" prop="files">
            <el-input
              @input="filesInput"
              v-model="form.files"
              placeholder="请输入附件张数"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="盘点数量：" prop="inventoryCount">
            <el-input v-model="form.inventoryCount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点金额：" prop="inventoryMoney">
            <el-input v-model="form.inventoryMoney" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="编制人：" prop="reportUsername">
            <el-input v-model="form.reportUsername" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制日期：" prop="reportTime">
            <el-input v-model="form.reportTime" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="业务事由：" prop="businessReason">
            <el-input
              v-model="form.businessReason"
              type="textarea"
              :rows="5"
              maxlength="400"
              placeholder="请输入业务事由"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="备注：" prop="remark">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="请输入备注"
              v-model="form.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <warehouseDialog
      @numrow="numrow"
      :reportInOrgName="form.reportInOrgName"
      :reportInOrgId="form.reportInOrgId"
      :isTrue="false"
      ref="warehouseDialog"
    />
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { getUserInfo, getReportInOrgData, qryUnderOrg } from "@/basa/api";
import { dateFormat1, proxyDateFormat } from "@/basa/utils";
import { showLoading } from "@/basa/utils/public";
import jsList from "../js";
import warehouseDialog from "@/app/financial/financialWriteOff/financialWriteOffAdd/components/warehouseDialog.vue";
export default {
  props: {
    detail: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    warehouseDialog
  },
  data() {
    return {
      jsList,
      isTrue: false,
      form: {
        reportInOrgId: "", // 填报单位
        reportInOrgName: "", // 填报单位
        departId: "", // 部门id
        departName: "", // 部门名称
        departCode: "", // 部门4A编码
        categoryName: "", //分类名称
        categoryCode: "", //分类编码
        inventoryCode: "", //盘点单编号
        inventoryName: "", //盘点单名称
        projectCode: "", // 项目编码
        projectName: "", // 项目名称
        standardMoneyCode: "", // 本位币编码
        standardMoney: "", // 本位币币种
        valoremMethodCode: "", // 计税方式编码
        valoremMethod: "", // 计税方式
        files: "", // 附件张数
        inventoryCount: "", //盘点数量
        inventoryMoney: "", //盘点金额
        inventoryWithoutmoney: "", //不含税金额
        warehouseName: "", //仓库
        warehouseCode: "", //仓库编码
        warehouseId: "", //仓库id
        reportUsername: "", //编制人
        reportTime: "", //编制日期
        businessReason: "", // 业务事由
        remark: "", //备注
        isProfit: 2 // 是否盈亏 0 盘盈，1盘亏 2 盘0
      },
      rules: {
        reportInOrgId: [
          { required: true, message: "请选择填报单位", trigger: "blur" }
        ],
        departName: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        // inventoryCode: [
        //   { required: true, message: "请输入盘点单编号", trigger: "blur" }
        // ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" }
        ],
        standardMoney: [
          { required: true, message: "请输入本位币币种", trigger: "blur" }
        ],
        valoremMethod: [
          { required: true, message: "请选择计税方式", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ],
        files: [{ required: true, message: "请输入附件张数", trigger: "blur" }],
        inventoryName: [
          { required: true, message: "请输入盘点单名称", trigger: "blur" }
        ],
        warehouseName: [
          { required: true, message: "请选择仓库", trigger: "change" }
        ],
        businessReason: [
          { required: true, message: "请输入业务事由", trigger: "change" }
        ]
      },
      // openId
      userOpenId: "",
      // 填报单位
      reportOptions: [],
      departOptions: [] // 部门
    };
  },
  computed: {
    ...mapGetters(["getPurchaseListData", "getInventoryCount", "getIsProfit"])
  },
  mounted() {
    this.init();
  },
  watch: {
    getPurchaseListData: {
      handler(newVal) {
        this.form.categoryName = newVal.categoryName;
        this.form.categoryCode = newVal.categoryCode;
      },
      deep: true
    },
    getInventoryCount(newVal) {
      this.form.inventoryCount = newVal.setCount;
      this.form.inventoryMoney = newVal.setMoney;
      this.form.inventoryWithoutmoney = newVal.setOutMoney;
    },
    getIsProfit: {
      handler(newVal) {
        this.isProfit = newVal;
      }
    }
  },
  methods: {
    init() {
      this.getUserInfo();
      if (this.detail.state === "create") {
        this.form.reportTime = dateFormat1(new Date());
      } else {
        this.form = {
          ...this.detail.inventoryBO,
          // 入库时间
          approvalAdoptTime:
            this.detail.inventoryBO.approvalAdoptTime !== null
              ? proxyDateFormat(this.detail.inventoryBO.approvalAdoptTime)
              : "",
          // 处理编制日期
          reportTime:
            this.detail.inventoryBO.reportTime !== null
              ? proxyDateFormat(this.detail.inventoryBO.reportTime)
              : "",
          // 盘点数量
          inventoryCount:
            this.detail.inventoryBO.inventoryCount !== null
              ? Number(this.detail.inventoryBO.inventoryCount).toFixed(3)
              : "",
          // 盘点金额
          inventoryMoney:
            this.detail.inventoryBO.inventoryMoney !== null
              ? Number(this.detail.inventoryBO.inventoryMoney).toFixed(2)
              : ""
        };
      }
    },
    // 用户信息
    getUserInfo() {
      getUserInfo(
        this.$addUrlPerFix(process.env.VUE_APP_BASEP_URL) +
          "/apis/basap/getUserInfo",
        {}
      ).then(res => {
        this.form.reportUsername = res.data.data.userInfo.name;
        this.form.compileUserId = res.data.data.userInfo.id;
        this.userOpenId = res.data.data.userInfo.openId;
        this.getReportInOrgData(this.userOpenId);
      });
    },
    // 填报单位
    getReportInOrgData(openId) {
      this.formLoading = showLoading();
      getReportInOrgData({ openIds: [openId] }).then(res => {
        this.reportOptions = res.data.data[this.userOpenId];
        const tempObj = this.reportOptions[0];

        this.form.reportInOrgName = tempObj.name;
        this.form.reportInOrgId = tempObj.orgId;
        this.getDepartData(tempObj.orgId);
        this.$nextTick(() => {
          this.isTrue = true;
          this.formLoading.close();
        });
      });
    },

    // 填报单位change事件
    changeReportInOrgId(val) {
      this.form.categoryName = "";
      this.form.categoryCode = "";
      this.form.warehouseCode = "";
      this.form.warehouseName = "";
      this.form.warehouseId = "";
      this.form.inventoryCount = "";
      this.form.inventoryMoney = "";
      this.setReportChange(true);
      this.setInventoryStatus(false);
      this.getDepartData(val);
    },

    // 部门 start
    async getDepartData(parentId) {
      const {
        child,
        child: [{ id, abbrName, autoCode }]
      } = (
        await qryUnderOrg({
          parentId, // 全局 其他【此组件是本级及以下】
          flag: "1" // 0 公司 1 部门 2 成员
        })
      ).data.data[0];
      this.departOptions = child;
      // 默认第一个部门
      this.form.departId = id;
      this.form.departName = abbrName;
      this.form.departCode = autoCode;
    },

    // 部门选中的数据
    handleNodeClick({ id, abbrName, autoCode }) {
      this.form.departId = id;
      this.form.departName = abbrName;
      this.form.departCode = autoCode;
      this.$refs.selectTree.blur();
    },
    // 部门 end

    //打开仓库
    handleWarehouse() {
      this.$refs.warehouseDialog.dialogVisible = true;
      this.$refs.warehouseDialog.getContractList(
        this.$refs.warehouseDialog.formData
      );
    },
    //选择仓库
    numrow(data) {
      this.form.warehouseId = data.id;
      this.form.warehouseName = data.warehouseName;
      this.form.warehouseCode = data.warehouseCode;
      this.form.projectCode = data.projectCode;
      this.form.projectName = data.projectName;
      this.form.standardMoneyCode = data.standardMoneyCode;
      this.form.standardMoney = data.standardMoney;
      this.form.valoremMethodCode = data.valoremMethodCode;
      this.form.valoremMethod = data.valoremMethod;
      this.setBusinessList(data.id);
      this.setInventoryStatus(!!data.warehouseName);
      this.setReportChange(true);
    },
    // 限制附件张树
    filesInput(val) {
      if (!/^[1-9]\d*$/.test(val)) {
        this.form.files = "";
      }
    },
    // 提交表单验证
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs["form"].validate(valid => {
          if (!valid) return reject("first");
          resolve(this.form);
        });
      });
    },
    ...mapActions(["setBusinessList", "setInventoryStatus", "setReportChange"])
  }
};
</script>

<style scoped lang="scss">
/deep/ .elInput .el-input {
  width: 260px;
}
/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}
</style>
